/**
 * AES 加密
 */
import CryptoJS from 'crypto-js'

export default class CryptoUtil {
  init(isTest) {
    this.isTest = isTest
  }
  setKey(key) {
    this.key = key
    // eslint-disable-next-line no-undef
    this.cipherOption = { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }
  }
  // 设置rsa加密后的AESKey
  setRSAEncryptKey(key) {
    this.RSAEncryptKey = key
  }
  // 获取rsa加密后的AESKey
  getRSAEncryptKey() {
    return this.RSAEncryptKey
  }
  getKey() {
    return this.key
  }
  getEncryptKey() {
    if (!this.key) {
      console.error('未设置key')
      return ''
    }
    // eslint-disable-next-line no-undef
    return CryptoJS.enc.Utf8.parse(this.key)
  }
  /**
   * 对加密数据进行utf8转换
   * @param {*} data
   * @returns
   */
  getSrcs(data) {
    // eslint-disable-next-line no-undef
    return CryptoJS.enc.Utf8.parse(data)
  }
  /**
   * 获取加密数据
   * @param {*} data
   * @returns
   */
  getEncryptedStr(data) {
    const srcs = this.getSrcs(data)
    const key = this.getEncryptKey()
    // eslint-disable-next-line no-undef
    const encryptedStr = CryptoJS.AES.encrypt(srcs, key, this.cipherOption).toString()
    if (this.isTest) {
      console.log('----------加密后数据----------')
      console.log(encryptedStr)
      this.decrypt(encryptedStr)
    }
    return encryptedStr
  }
  /**
 * 加密
 * @param {*} data 需要加密的数据，string或object
 * @returns
 */
  encrypt(data) {
    data = this.toStr(data)
    if (!data) {
      return ''
    }
    if (typeof (data) === 'object') {
      data = JSON.stringify(data)
    }
    if (this.isTest) {
      console.log('----------被加密数据----------')
      console.log(data)
      console.log('----------加密key(只在测试环境会打印)----------')
      console.log(this.key)
    }
    // 加密数据
    return this.getEncryptedStr(data)
  }
  toStr(data) {
    if (!data) {
      return ''
    }
    if (typeof (data) === 'object') {
      data = JSON.stringify(data)
    }
    return data
  }
  /**
 * 解密
 * @param {*} data string或object
 * @returns
 */
  decrypt(data) {
    data = this.toStr(data)
    if (!data) {
      return ''
    }
    if (this.isTest) {
      console.log('----------解密数据----------')
      console.log(data)
      console.log('----------解密key----------')
      console.log(this.key)
    }
    const key = this.getEncryptKey()

    // eslint-disable-next-line no-undef
    const decrypt = CryptoJS.AES.decrypt(data, key, this.cipherOption)
    // eslint-disable-next-line no-undef
    const decryptStr = CryptoJS.enc.Utf8.stringify(decrypt).toString()
    if (this.isTest) {
      console.log('----------解密后数据(只在测试环境会打印)----------')
      console.log(decryptStr)
    }
    let decryptObj = decryptStr
    try {
      decryptObj = JSON.parse(decryptStr)
    } catch (e) {
      console.warn('数据类型转换失败:' + decryptStr)
      console.warn(e)
    }
    return decryptObj
  }
}
